import { ObjectCopy } from '@/util'
import { setLocal, setLocalMenus } from '@/util/storage'
import { getMenuData } from '@api/menu'
const handleMenuToMap = (menus = []) =>
  menus.reduce((arr, menu) => {
    const { route, langkey, children } = menu
    arr.push(
      {
        route,
        langkey
      },
      ...handleMenuToMap(children)
    )
    return arr
  }, [])

export default {
  namespaced: true,
  state: () => ({
    menus: [],
    menusMap: [],
    collapse: false,
    activeMenu: 'Home',
    activeMenus: [
      {
        route: 'Home',
        langkey: 'title_aat_h',
        lock: true
      }
    ]
  }),
  getters: {
    get: state => key => state[key],
    getMap: state => key => {
      const obj = {
        route: '',
        langkey: ''
      }
      state.menusMap.forEach(
        item => key === item.route && ObjectCopy(obj, item)
      )
      return obj
    }
  },
  mutations: {
    set(state, store) {
      const { key, data } = store || {}
      state[key] = data
    },
    addActiveMenu(state, data) {
      state.activeMenus.push(data)
    },
    clearActiveMenu(state) {
      state.activeMenus.splice(1)
    },
    delActiveMenu(state, index) {
      state.activeMenus.splice(index, 1)
    }
  },
  actions: {
    async setMenus({ commit }, storage) {
      const key = 'menus'
      let menu, map
      if (storage) {
        ;({ menu, map } = storage)
      } else {
        const { data } = await getMenuData()
        if (data) {
          menu = { key, data }
          map = {
            key: key + 'Map',
            data: handleMenuToMap(data)
          }
          setLocal('menu/setMenus', { menu, map })
        }
      }
      commit('set', menu)
      commit('set', map)
    },
    setCollapse({ commit }, data) {
      const key = 'collapse'
      commit('set', { key, data })
      setLocal('menu/setCollapse', data)
    },
    setActiveMenu({ commit }, data) {
      const key = 'activeMenu'
      commit('set', { key, data })
    },
    setActiveMenus({ commit }, data = []) {
      data.forEach(item => commit('addActiveMenu', item))
    },
    addActiveMenu({ commit, state }, data) {
      commit('addActiveMenu', data)
      setLocalMenus(state.activeMenus)
    },
    delActiveMenu({ commit, state }, index) {
      commit('delActiveMenu', index)
      setLocalMenus(state.activeMenus)
    },
    clearActiveMenu({ commit }) {
      commit('clearActiveMenu')
    }
  }
}
